<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"> </el-alert>
      <!-- 商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择的商品分类：</span>
          <!-- @change="parentCateChange"  -->
          <el-cascader v-model="selectCateKeys" :options="cateList" :props="cateProps" @change="parentCateChange" clearable></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签页区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="!selectCateKeys.length" @click="addParamsDialogVisible = true">添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div class="ml">
                  <el-tag v-for="(item, idx) in scope.row.attr_vals" :key="idx" closable @close="handleClose(idx, scope.row)">{{ item }}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input class="el-inputval" v-if="scope.row.inputVisible" v-model.trim="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                  <!-- 添加按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="!selectCateKeys.length" @click="addParamsDialogVisible = true">添加属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div class="ml">
                  <el-tag v-for="(item, idx) in scope.row.attr_vals" :key="idx" closable @close="handleClose(idx, scope.row)">{{ item }}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input class="el-inputval" v-if="scope.row.inputVisible" v-model.trim="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                  <!-- 添加按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <input type="hidden" :name="scope" />
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog :title="`添加${activeName === 'many' ? '动态参数' : '静态属性'}`" :visible.sync="addParamsDialogVisible" width="50%" @close="addParamsDialogClose">
      <el-form :model="addForm" status-icon :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="activeName === 'many' ? '动态参数' : '静态属性'" prop="attr_name">
          <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改参数对话框 -->
    <el-dialog :title="`编辑${activeName === 'many' ? '动态参数' : '静态属性'}`" :visible.sync="editParamsDialogVisible" width="50%" @close="editParamsDialogClose">
      <el-form :model="editForm" status-icon :rules="addFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="activeName === 'many' ? '动态参数' : '静态属性'" prop="attr_name">
          <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCateList, getCateParams, addCateParams, editCateParams, delCateParams } from '@/api'
export default {
  name: 'GoodsParams',
  data() {
    return {
      cateList: [],
      selectCateKeys: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被激活的页签名称
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      // 添加按钮弹出控制
      addParamsDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 编辑参数控制
      editParamsDialogVisible: false,
      editForm: {
        attr_name: '',
        id: ''
      }
    }
  },
  async created() {
    const { data: res } = await getCateList({ type: 3 })
    if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
    console.log(res.data)
    this.cateList = res.data
  },
  methods: {
    // 获取参数列表数据
    async getParamsData() {
      // console.log(this.selectCateKeys)
      if (this.cateId) {
        const { data: res } = await getCateParams(this.cateId, this.activeName)
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        res.data.forEach((ele) => {
          if (ele.attr_vals) {
            ele.attr_vals = ele.attr_vals.split(' ')
          } else {
            ele.attr_vals = []
          }
          // 控制文本框显示与隐藏
          ele.inputVisible = false
          // 文本框中输入的值
          ele.inputValue = ''
        })
        // this.$message.success('获取参数成功')
        console.log(res)
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      }
    },
    // 级联选择器改变事件
    parentCateChange() {
      if (this.selectCateKeys.length !== 3) {
        return (this.selectCateKeys = [])
      }
      this.getParamsData()
    },
    // Tab页签点击事件
    handleTabClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    // 添加对话框关闭事件
    addParamsDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加对话框确定事件
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return ''
        const { data: res } = await addCateParams(this.cateId, this.addForm.attr_name, this.activeName)
        if (res.meta.status !== 201) return this.message.error('添加失败')
        this.$message.success('添加成功')
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    // 编辑参数点击事件
    showEditDialog(val) {
      console.log(val)
      this.editForm.attr_name = val.attr_name
      this.editForm.id = val.attr_id
      this.editParamsDialogVisible = true
    },
    // 编辑弹框关闭事件
    editParamsDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑弹框确定事件
    editParams() {
      const idObj = { cid: this.cateId, attrId: this.editForm.id }
      const paramsObj = { name: this.editForm.attr_name, sel: this.activeName }
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return ''
        const { data: res } = await editCateParams(idObj, paramsObj)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    // 删除参数
    async delParams(attrId) {
      // console.log(attrId)
      const idObj = { cid: this.cateId, attrId }
      const ress = await this.$confirm('此操作将永久删除此参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (ress === 'confirm') {
        const { data: res } = await delCateParams(idObj)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParamsData()
      }
    },
    // 添加标签确认事件（回车和失去焦点）
    async handleInputConfirm(val) {
      if (!val.inputValue) return (val.inputVisible = false)
      val.attr_vals.push(val.inputValue)
      const idObj = { cid: this.cateId, attrId: val.attr_id }
      const paramsObj = { name: val.attr_name, sel: val.attr_sel, vals: val.attr_vals.join(' ') }
      const { data: res } = await editCateParams(idObj, paramsObj)
      // console.log(res)
      if (res.meta.status !== 200) {
        val.attr_vals.pop()
        return this.$message.error('添加失败')
      }
      this.$message.success('添加成功')
      val.inputValue = ''
      val.inputVisible = false
      console.log('ok')
    },
    // 显示输入框事件
    showInput(val) {
      val.inputVisible = true
      // 当页面被重新渲染后才会执行代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签事件
    async handleClose(i, val) {
      val.attr_vals.splice(i, 1)
      const idObj = { cid: this.cateId, attrId: val.attr_id }
      const paramsObj = { name: val.attr_name, sel: val.attr_sel, vals: val.attr_vals.join(' ') }
      const { data: res } = await editCateParams(idObj, paramsObj)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
    }
  },
  computed: {
    // 分类id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      } else {
        return null
      }
    }
  },
  watch: {
    // 侦听分类id变化，如果为null，清空这两项，让页面恢复无数据状态
    cateId(val) {
      if (!val) {
        this.manyTableData = []
        this.onlyTableData = []
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.ml {
  padding-left: 65px;
}
.el-tag {
  margin: 5px 10px;
  &:nth-child(1) {
    margin: 0;
    margin-right: 10px;
  }
}
.el-inputval {
  width: 90px;
}
</style>
